package com.fair.concurrency.example.sync;

import java.util.concurrent.*;
import java.util.stream.IntStream;

/**
 * 某一线程在开始运行前等待 n 个线程执行完毕。
 *
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/9/23 16:16
 */
public class CountDownLatchTest
{
    private static final int size = 8;

    public static void main(String[] args) throws InterruptedException
    {
        //1.固定线程数与CountDownLatch数保持一致
        //ExecutorService executorService = Executors.newFixedThreadPool(size);
        //2.固定线程数与CountDownLatch数不保持一致
        ExecutorService executorService = new ThreadPoolExecutor(7,10, 0, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>());
        CountDownLatch countDownLatch = new CountDownLatch(size);
        IntStream.range(0, size).forEach(
                r -> executorService.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + " start countDownLatch Test" + r);
                    try
                    {
                        Thread.sleep(1000);//模拟耗时操作
                    } catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                    System.err.println(Thread.currentThread().getName() + " end countDownLatch Test" + r);
                    countDownLatch.countDown();
                    System.out.println("count:"+countDownLatch.getCount());
                })
        );
        countDownLatch.await();
        executorService.shutdown();
        System.out.println("Finish countDownLatch Test");
    }
}
